﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Workflow.Alerts.Utils;
using Workflow.Alerts;
using Sitecore.Data.Items;

namespace Workflow.Layout.Layouts
{
    public partial class SettingsLayout : BaseLayout
    {
        #region Events

        protected override void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);

            HideInvalidCss();
            SetNavigationLinks(lnkSettings, lnkProfile, lnkHelp, lnkLogo);
            ShowConfirmation.Value = user.Confirmation.ToString().ToLower();
            lnkProfile.Text = string.Format("{0} {1}", user.FirstName, user.LastName) + " [" + user.Name + "]";
            lblOrganizationName.Text = user.Name;
            MunicipalityName.Value = BranchName;

            if (!IsPostBack)
            {
                txtSearch.Text = GetSearchText();
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(txtSearch.Text))
            {
                lblSearchEmptyMsg.Visible = true;
                return;
            }

            Search(txtSearch.Text);
        }

        protected void lnkLogout_Click(object sender, EventArgs e)
        {
            Logout();
        }

        #endregion

        #region Private Methods

        protected override void SetMenuSources()
        {
            Menu1.DataSource = MenuSource;
            if (user.Type == WorkflowEnums.UserType.Municipality)
            {
                Menu1.AlertCount = Utils.GetMenuStatuses(user.TypeId, null);
            }
            else
            {
                Menu1.AlertCount = Utils.GetMenuStatuses(null, user.TypeId);
            }

            Menu2.DataSource = SubMenuSource;
        }

        private void HideInvalidCss()
        {
            if (Request.Browser.EcmaScriptVersion.Major <= 0 && Request.Browser.Frames == false && Request.Browser.Type == "Unknown" && Request.Browser.Browser == "Unknown")
            {
                phHideInvalidCss.Visible = false;
            }
        }

        protected override void SetTitle()
        {
            base.SetTitle();

            ItemAxes ia = new Sitecore.Data.Items.ItemAxes(Sitecore.Context.Item);
            Item[] iar = ia.GetAncestors();
            var title = (iar.Length >= 6) ? iar[5].Name : Sitecore.Context.Item.Name;
            lblHeaderTitle.Text = Translate.Words.Keys.Contains(title) ? Translate.Words[title] : title;
        }

        #endregion
    }
}
